package com.lyl.momanapp.activity;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.lyl.momanapp.R;
import com.lyl.momanapp.adapter.TwoTwoAdapter;
import com.lyl.momanapp.adapter.TwoTwoimgAdapter;
import com.lyl.momanapp.bean.URL;
import com.lyl.momanapp.face.contract.ModelActivityContract;
import com.lyl.momanapp.face.net.DetectWork;
import com.lyl.momanapp.face.utils.ConvertUtils;
import com.lyl.momanapp.face.utils.Utils;
import com.xinlan.imageeditlibrary.editimage.EditImageActivity;
import com.xinlan.imageeditlibrary.editimage.fliter.PhotoProcessing;
import com.xinlan.imageeditlibrary.editimage.utils.BitmapUtils;
import com.xps.face.bean.BitmapBean;
import com.xps.face.bean.FaceDetectResp;
import com.xps.face.entities.PointSimple;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.LinkedList;

import butterknife.BindView;
import butterknife.ButterKnife;
import jp.co.cyberagent.android.gpuimage.GPUImage;
import rx.Subscriber;

import static com.lyl.momanapp.R.id.beijing_Image;

/**
 * Created by lyl on 2017/11/6.
 */

public class FacedomeActivity extends AppCompatActivity implements TakePhoto.TakeResultListener, InvokeListener, ModelActivityContract.View {

    private static final String TAG = "AnalyzeActivity";
//    @BindView(R.id.xiangce_Button)
//    Button xiangceButton;

    @BindView(beijing_Image)
    ImageView beijingImage;

    @BindView(R.id.faxing)
    ImageView faxing;
    @BindView(R.id.lian_dong_rl_name)
    RecyclerView mRl;
    @BindView(R.id.lian_dong_rl_img)
     RecyclerView mRlimg;
    @BindView(R.id.two_but)
    Button but;

    private String picturePath = "";
    String filename = "";
    int width;
    int height;
    private TakePhoto takePhoto;
    FaceDetectResp.FacesBean.LandmarkBean landmarkBean;
    @BindView(R.id.face_Image)
    ImageView faceImage;
    Bitmap topBitmap = null;
    Bitmap getTopBitmap = null;
    private CropOptions cropOptions;
//    @BindView(R.id.zhaoxiang_Button)
//    Button zhaoxiangButton;
    static final int REQUEST_CODE_CAPTURE_CROP_PHOTO = 1;
    private InvokeParam invokeParam;
    private int imageWidth, imageHeight;//
    private Bitmap mainBitmap;
    private WeakReference<Bitmap> resultBitmapRef;
    private BeautyTask handleTask;
    private Bitmap afterBitmap;
    private Paint paint;
    private Canvas canvas;
    private Dialog dialog;
    private View inflate;
    GPUImage gpuImage;
    BitmapBean bitmapBean = new BitmapBean();
    private TwoTwoAdapter twoTwoAdapter;
    private TwoTwoimgAdapter twoTwoimgAdapter;
    private ImageView mFaceZhaoXiang;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frament_two_two);
        ButterKnife.bind(this);
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(ConvertUtils.REFERENCE_WIDTH).setAspectY(ConvertUtils.REFERENCE_HEIGHT);
        builder.setOutputX(ConvertUtils.REFERENCE_WIDTH).setOutputY(ConvertUtils.REFERENCE_HEIGHT);
        cropOptions = builder.create();
//        faceImage.setOnTouchListener(new MulitPointTouchListener());
//        faxing.setOnTouchListener(new MulitPointTouchListener());
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels;
        imageHeight = metrics.heightPixels;
        faceImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show1();
                Log.i("11111111111", "onClick: "+11111111);
            }
        });
//        zhaoxiangButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(genFilePath()), cropOptions);
//                // startActivity(new Intent(MainActivity.this, FaceCaptureActivity.class));
//            }
//        });
//        xiangceButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                getTakePhoto().onPickFromGalleryWithCrop(Uri.fromFile(genFilePath()), cropOptions);
//            }
//        });
//        meiyanButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                File outputFile = FileUtils.genEditFile();
//                EditImageActivity.start(FacedomeActivity.this, Environment.getExternalStorageDirectory() + File.separator + "asdasd.jpg", outputFile.getAbsolutePath(), REQUEST_CODE_CAPTURE_CROP_PHOTO);
//            }
//        });

//                faxing.setImageDrawable(getResources().getDrawable(R.drawable.faxing_image_2));
//       getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(genFilePath()), cropOptions);
//        getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(new File(URL.imgURL)), cropOptions);
        addListenersrl();
        if (URL.imgURL==null){

        }else {
            JsonBean(URL.imgURL);
        }
    }
    public  void show1(){
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        inflate = LayoutInflater.from(this).inflate(R.layout.item_face, null);
        mFaceZhaoXiang = (ImageView)inflate.findViewById(R.id.face_zhaoxiao);
        mFaceZhaoXiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(genFilePath()), cropOptions);
            }
        });
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = getWindowManager().getDefaultDisplay().getWidth();
        lp.y = 20;//设置Dialog距离底部的距离
        //       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框

    }
    public void addListenersrl() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRl.setLayoutManager(linearLayoutManager);
        mRl.setHasFixedSize(true);
        twoTwoAdapter = new TwoTwoAdapter(new String[]{"头发","眼睛","鼻子","眉毛"});
        mRl.setAdapter(twoTwoAdapter);
        twoTwoAdapter.setOnItemClickLitener(new TwoTwoAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(TextView view, int position) {
            if (position==0){
                twoTwoimgAdapter.showDataString(new String[]{"1","2"});
            }else {
                twoTwoimgAdapter.showDataString(new String[]{});
            }
            }
        });
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRlimg.setLayoutManager(linearLayoutManager2);
        mRlimg.setHasFixedSize(true);
        twoTwoimgAdapter = new TwoTwoimgAdapter(new String[]{},this);
        mRlimg.setAdapter(twoTwoimgAdapter);
        twoTwoimgAdapter.setOnItemClickLitener(new TwoTwoimgAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(ImageView view, int position) {
                        if (position==0){
                            faxing.setImageDrawable(getResources().getDrawable(R.drawable.faxing_image_1));
                        }else {
                            faxing.setImageDrawable(getResources().getDrawable(R.drawable.faxing_image_2));
                        }
            }
        });
        but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    public void doBeautyTask() {
        if (handleTask != null && !handleTask.isCancelled()) {
            handleTask.cancel(true);
        }

        handleTask = new BeautyTask(0, 5);
        handleTask.execute(0);
    }


    private final class BeautyTask extends AsyncTask<Integer, Void, Bitmap> {
        private float smoothVal;
        private float whiteVal;

        private Bitmap srcBitmap;

        public BeautyTask(float smooth, double white) {
            this.smoothVal = smooth;
            this.whiteVal = (float) white;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(Integer... params) {
            srcBitmap = Bitmap.createBitmap(getTopBitmap.copy(
                    Bitmap.Config.ARGB_8888, true));
            PhotoProcessing.handleSmoothAndWhiteSkin(srcBitmap, smoothVal, whiteVal);
            return srcBitmap;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (result == null)
                return;

            resultBitmapRef = new WeakReference<Bitmap>(result);
            try {
                saveFile(resultBitmapRef.get(), "asdasd.jpg");
                JsonBean(Environment.getExternalStorageDirectory() + File.separator + "asdasd.jpg");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 获得一个图片地址
     */
    File genFilePath() {
        File Gallery = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!Gallery.getParentFile().exists()) Gallery.getParentFile().mkdirs();
        return Gallery;
    }

    /**
     * 获取TakePhoto实例
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    public void setBitmap(String top, Path clipPath) throws IOException {
        this.topBitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(top), 480, 640, false);//fun(,clipPath);
        topBitmap = bitmapBean.fun(topBitmap, clipPath);
        //saveFile(topBitmap, "asdasd.jpg");
        //faceImage.setImageBitmap(topBitmap);
        //faceImage.setPadding(320,200,0,0);
        Drawable drawable =new BitmapDrawable(topBitmap);
        faceImage.setBackgroundDrawable(drawable);

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    Path getMouthPath(LinkedList<PointSimple> points) {
        Path path = new Path();
        PointSimple p0 = points.get(0);
        path.moveTo(p0.width_scale, p0.height_scale);
        for (PointSimple ps : points) {
            path.lineTo(ps.width_scale, ps.height_scale);
            Log.e("getMouthPath", ps.width_scale + "----" + ps.height_scale);
        }
        path.lineTo(p0.width_scale, p0.height_scale);
        path.close();
        return path;
    }


    public void saveFile(Bitmap bm, String fileName) throws IOException {
        String path = Environment.getExternalStorageDirectory() + File.separator;
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }
            //调用这个方法
    public void JsonBean(String str) {
        final String file = str;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;
        height = dm.heightPixels;
        DetectWork.doDetect(Utils.getImageStr(file), new Subscriber<FaceDetectResp>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(FaceDetectResp faceDetectResp) {
                if (faceDetectResp.getFaces() == null || faceDetectResp.getFaces().size() < 1)
                    return;
                landmarkBean = faceDetectResp.getFaces().get(0).getLandmark();
                Path path = getMouthPath(ConvertUtils.getPoints(landmarkBean, width, height));
                try {
                    setBitmap(file, path);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }


    @Override
    public void takeSuccess(TResult result) {
        //getTopBitmap = GPUImageUtil.getGPUImageFromAssets(this, gpuImage, 12, result.getImage().getOriginalPath());
        getTopBitmap = BitmapFactory.decodeFile(result.getImage().getOriginalPath());

        doBeautyTask();
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("onActivityResult", "" + requestCode);
        if (requestCode == 1) {
            handleEditorImage(data);
        } else {
            getTakePhoto().onActivityResult(requestCode, resultCode, data);
        }
    }




    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    private void handleEditorImage(Intent data) {
        String newFilePath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT);
        boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false);
        if (isImageEdit) {
            //Toast.makeText(this, getString(R.string.rotate, newFilePath), Toast.LENGTH_LONG).show();
        } else {//未编辑  还是用原来的图片
            newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH);
        }
        Log.d("image is edit", isImageEdit + "");
        LoadImageTask loadTask = new LoadImageTask();
        loadTask.execute(newFilePath);
    }

    private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {
            return BitmapUtils.getSampledBitmap(params[0], imageWidth / 4, imageHeight / 4);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (mainBitmap != null) {
                mainBitmap.recycle();
                mainBitmap = null;
                System.gc();
            }
            mainBitmap = result;
            faceImage.setImageBitmap(mainBitmap);
        }
    }// end inner class


}